# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 18:58:02 2020

@author: wjx
"""
import re

#加减乘除的正则表达式


def cheng_cal(cal):
    """
    计算乘法
    """
    num1, num2 = cal.split('*')
    return str(float(num1) * float(num2))

def chu_cal(cal):
    """
    计算除法
    """
    num1, num2 = cal.split('/')
    num = float('%.2f'% (float(num1) / float(num2)))
    return str(num)

def jia_cal(cal):
    """
    计算加法
    """
    num1, num2 = cal.split('+')
    return str(float(num1) + float(num2))

def jian_cal(cal):
    """
    计算减法
    """
    jian = '(?P<num1>\d+(\.\d+)?)-(?P<num2>-?\d+(\.\d+)?)'
    ret = re.search(jian, cal)
    num1 = ret.group('num1')
    num2 = ret.group('num2')
    return str(float(num1) - float(num2))

def chengchu(cal):
    """
    匹配乘除法
    """
    cheng = '\d+(\.\d+)?\*-?\d+(\.\d+)?'
    chu = '\d+(\.\d+)?/-?\d+(\.\d+)?'
    while '*' in cal:
        ret = re.search(cheng, cal).group()
        res = cheng_cal(ret)
        cal = cal.replace(ret, res ,1)
    while '/' in cal:
        ret = re.search(chu, cal).group()
        res = chu_cal(ret)
        cal = cal.replace(ret, res ,1)
    return cal

def jiajian(cal):
    """
    匹配加减法
    """
    jia = '\d+(\.\d+)?\+-?\d+(\.\d+)?'
    jian = '\d+(\.\d+)?--?\d+(\.\d+)?'
    while '+' in cal:
        ret = re.search(jia, cal).group()
        res = jia_cal(ret)
        cal = cal.replace(ret, res,1)
   
    while '-' in cal:
        ret = re.search(jian, cal)
        if ret:
            ret = ret.group()
            res = jian_cal(ret)
            cal = cal.replace(ret, res,1)
            
        else:
            break
    return cal


def kuohao(cal):
    kuohao = '\([^()]+\)'
    ret = re.search(kuohao, cal)
    return ret.group()


def main():
    cal_str = '1 - 2*( (60-30 +(-40/5)* (9-2*5/3 + 7 /3*99/4*2998+10 * 568/14)) - (-4*3)/ (16-3*2) )'
    cal_str = cal_str.replace(' ','')
    while '(' in cal_str:
        sub_kuohao = kuohao(cal_str) #匹配括号内的内容
        sub_chengchu = chengchu(sub_kuohao[1:-1])
        sub_jiajian = jiajian(sub_chengchu)
        cal_str = cal_str.replace(sub_kuohao, sub_jiajian, 1)
    sub_chengchu = chengchu(cal_str)
    sub_jiajian = jiajian(sub_chengchu)
    cal_str = cal_str.replace(sub_kuohao, sub_jiajian, 1)
    print(cal_str)
    
if __name__ == '__main__':
    main()
